<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="0px" class="top-left">
      <el-form-item label="" prop="dpmId">
        <el-select v-model="queryParams.dpmId" clearable placeholder="请选择所属科室">
          <el-option v-for="item in bsDataReportList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="instruName">
        <el-input v-model="queryParams.instruName" placeholder="请输入仪器名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb5 top-right-btn small-line-height">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['dept:bsInstrument:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['dept:bsInstrument:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['dept:bsInstrument:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['dept:bsInstrument:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['dept:bsInstrument:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleImportMB">模版下载</el-button>
      </el-col>

      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table border stripe class="table" v-loading="loading" :data="bsInstrumentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属科室" align="center" prop="dpmId" min-width="120" show-overflow-tooltip />
      <el-table-column label="仪器名称" align="center" prop="instruName" min-width="120" show-overflow-tooltip />
      <el-table-column label="仪器编号" align="center" prop="instruCode" min-width="120" show-overflow-tooltip />
      <el-table-column label="生产厂家名称" align="center" prop="manufacturer" min-width="120" show-overflow-tooltip />
      <el-table-column label="型号规格" align="center" prop="model" min-width="120" show-overflow-tooltip />
      <el-table-column label="测量范围" align="center" prop="measuringRange" min-width="120" show-overflow-tooltip />
      <el-table-column label="出厂编号" align="center" prop="manufacturerCode" min-width="120" show-overflow-tooltip />
      <el-table-column label="出厂日期" align="center" prop="manufacturerDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.manufacturerDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="购置日期" align="center" prop="purchaseDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保管者" align="center" prop="custodian" width="120" show-overflow-tooltip />
      <el-table-column label="检定校准单位" align="center" prop="calibrationUnit" width="120" show-overflow-tooltip />
      <el-table-column label="检定校准时间" align="center" prop="calibrationDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.calibrationDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效截至日期" align="center" prop="effectiveDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.effectiveDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="自动生成记录0否1是" align="center" prop="recordFlag" width="100" show-overflow-tooltip /> -->
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="160">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['dept:bsInstrument:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['dept:bsInstrument:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改试验室仪器对话框 -->
    <bs-instrument-add-or-update ref="addOrUpdate" @callBack="getList" />
    <!-- 导入 -->
    <!-- <jy-dialog title="试验室仪器导入" :visible.sync="importOpen" width="800px" append-to-body>
      <el-form ref="importForm" :rules="rules" :model="importForm" label-width="80px">
        <el-form-item label="文件" prop="file">
          <upload v-model="importForm.file" @uploadTF="uploadTF" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel">取 消</el-button>
      </div>
    </jy-dialog> -->
    <jy-dialog title="试验室仪器导入" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&deptId=' + this.$store.state.dept.deptId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的仪器数据</div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="handleImportMB">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitFileForm">确 定</el-button>
        <el-button size="small" @click="upload.open = false">取 消</el-button>
      </div>
    </jy-dialog>
  </div>
</template>

<script>
import { listBsInstrument, delBsInstrument } from "@/api/dept/bsInstrument";
import { listBsDepartment } from "@/api/dept/bsDepartment";
import { mapGetters } from "vuex";
import BsInstrumentAddOrUpdate from "./BsInstrumentAddOrUpdate.vue";
import DeptTreeSelect from "@/components/DeptTreeSelect";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import upload from "./upload.vue";
import { getToken } from "@/utils/auth";

export default {
  name: "BsInstrument",
  components: {
    BsInstrumentAddOrUpdate,
    DeptTreeSelect,
    Treeselect,
    upload
  },
  data() {
    return {
      bsDataReportList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试验室仪器表格数据
      bsInstrumentList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dpmId: undefined,
        deptId: undefined,
        instruName: undefined,
        instruCode: undefined,
        manufacturer: undefined,
        model: undefined,
        measuringRange: undefined,
        manufacturerCode: undefined,
        manufacturerDate: undefined,
        purchaseDate: undefined,
        custodian: undefined,
        calibrationUnit: undefined,
        calibrationDate: undefined,
        effectiveDate: undefined,
        recordFlag: undefined
      },
      importOpen: false,
      importForm: {
        file: null,
        deptId: null
      },
      rules: {
        file: [{ required: true, message: "请选择上传的文件", trigger: "change" }]
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },

        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/dept/bsInstrument/importData"
      }
    };
  },

  // 监听顶部全局下拉
  computed: {
    ...mapGetters(["deptId"]),
    treeData: {
      get() {
        return this.$store.state.dept.deptTreeList;
      }
    }
  },
  watch: {
    deptId(newValue, oldValue) {
      this.queryParams.deptId = newValue;
      this.getList(1);
    }
  },

  created() {
    this.getList(0);
    this.getlistBsDepartment();
  },
  methods: {
    getlistBsDepartment() {
      console.log(this.deptId);

      this.loading = true;
      listBsDepartment({ deptId: this.deptId }).then((response) => {
        this.bsDataReportList = response.rows;
        this.loading = false;
      });
    },
    /** 查询试验室仪器列表 */
    getList(num) {
      this.loading = true;
      num ? this.queryParams.deptId : (this.queryParams.deptId = this.deptId);
      listBsInstrument(this.queryParams).then((response) => {
        this.bsInstrumentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.instruId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.addOrUpdate.init();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const instruId = row.instruId || this.ids;
      this.$refs.addOrUpdate.init(instruId);
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const instruIds = row.instruId || this.ids;
      this.$modal
        .confirm('是否确认删除试验室仪器编号为"' + instruIds + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delBsInstrument(instruIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "dept/bsInstrument/export",
        {
          ...this.queryParams
        },
        `bsInstrument_${new Date().getTime()}.xlsx`
      );
    },
    handleImport() {
      this.upload.open = true;
      // this.importOpen = true;
    },
    handleImportMB() {
      this.download(
        "dept/bsInstrument/exportTemplateOne",
        {
          ...this.queryParams
        },
        `bsInstrument_${new Date().getTime()}.xlsx`
      );
    },
    cancel() {
      this.importOpen = false;
      this.importForm = {
        file: null,
        deptId: null
      };
      this.resetForm("importForm");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["importForm"].validate((valid) => {
        if (valid) {
          // /dept/bsInstrument/importData
        }
      });
    },
    uploadTF() {
      this.importOpen = false;
    },
    async handleUpload(param) {
      let formData = new FormData();
      formData.append("file", param.file);
      formData.append("deptId", this.$store.state.dept.deptId); //传projectId
      const configs = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      const res = await upLoading(formData, configs);
      console.log(res);
      // this.$message
      // this.form.autograph = res.data.fileName;
      // this.imageUrl1 = res.data.fileUrl;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    }
  }
};
</script>
